package com.jovienne.web.sys_role.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jovienne.utils.ResultUtils;
import com.jovienne.utils.ResultVo;
import com.jovienne.web.sys_role.entity.*;
import com.jovienne.web.sys_role.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/role")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;

    //分配权限树数据回显查询
    @GetMapping("/getMenuTree")
    public ResultVo getMenuTree(RoleAssignParam param){
        RolePermissionVo tree = sysRoleService.getMenuTree(param);
        return ResultUtils.success("查询成功",tree);
    }

    //新增角色
    @PostMapping
    public ResultVo addRole(@RequestBody SysRole role){
        role.setCreateTime(new Date());
        boolean save = sysRoleService.save(role);
        if(save){
            return ResultUtils.success("新增成功!");
        }
        return ResultUtils.error("新增失败!");
    }
    //编辑角色
    @PutMapping
    public ResultVo editRole(@RequestBody SysRole role){
        role.setUpdateTime(new Date());
        boolean save = sysRoleService.updateById(role);
        if(save){
            return ResultUtils.success("编辑成功!");
        }
        return ResultUtils.error("编辑失败!");
    }
    //删除角色
    @DeleteMapping("/{roleId}")
    public ResultVo deleteRole(@PathVariable("roleId") Long
                                       roleId){
        boolean b = sysRoleService.removeById(roleId);
        if(b){
            return ResultUtils.success("删除成功!");
        }
        return ResultUtils.error("删除失败!");
    }
    //角色列表
    @GetMapping("/list")
    public ResultVo getList(RoleParam param){
        IPage<SysRole> list = sysRoleService.list(param);
        return ResultUtils.success("查询成功",list);
    }
    //根据角色id列表出劫色名称
    @GetMapping("getSelect")
    public ResultVo getListSelect() {
        List<SelectType> selectTypes =
                sysRoleService.list().stream()         //获取集合的流（这样可以避免判空，stream本身会处理空集合）
                .map(item -> {                         //声明：将两个需要的字段映射给selectType
                    SelectType selectType = new SelectType();
                    selectType.setValue(item.getRoleId());
                    selectType.setLabel(item.getRoleName());
                    return selectType;
                })
                .collect(Collectors.toList());         //声明：收集为list

        return ResultUtils.success("查询成功", selectTypes);
    }
}